const API_BASE_URL = 'http://localhost:2556/api';

let terminals = [];
let activeTerminalId = null;
let xtermInstances = {};
let currentUserId = '';

async function fetchTerminals(userId = '') {
  try {
    const url = userId ? `${API_BASE_URL}/terminals?userId=${userId}` : `${API_BASE_URL}/terminals`;
    const response = await fetch(url);
    const data = await response.json();
    
    if (data.success) {
      terminals = data.data.terminals;
      updateTerminalList();
      updateUserFilter();
    }
  } catch (error) {
    console.error('Failed to fetch terminals:', error);
  }
}

function updateTerminalList() {
  const listContainer = document.getElementById('terminal-list');
  
  if (terminals.length === 0) {
    listContainer.innerHTML = `
      <div class="text-center text-gray-500 dark:text-gray-400 py-4">
        <span class="material-symbols-outlined text-4xl mb-2">terminal</span>
        <p class="text-sm">暂无终端</p>
      </div>
    `;
    return;
  }
  
  listContainer.innerHTML = terminals.map(terminal => {
    const isActive = terminal.id === activeTerminalId;
    const statusColor = terminal.status === 'active' ? 'bg-green-500' : 'bg-gray-400 dark:bg-gray-600';
    const statusAnimation = terminal.status === 'active' ? 'animate-pulse' : '';
    const activeClass = isActive ? 'border-primary/50 bg-gray-100 dark:bg-gray-800' : 'border-transparent';
    
    const createdTime = new Date(terminal.created).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    
    return `
      <div class="p-3 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-800 cursor-pointer border ${activeClass} dark:border-${activeClass} hover:border-primary/50 dark:hover:border-primary/50" onclick="selectTerminal('${terminal.id}')">
        <div class="flex justify-between items-start">
          <div class="flex-grow">
            <div class="flex items-center gap-2">
              <span class="w-2 h-2 rounded-full ${statusColor} ${statusAnimation}"></span>
              <p class="text-sm font-semibold text-gray-900 dark:text-white truncate">${terminal.id.substring(0, 8)}</p>
            </div>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">user: ${terminal.userId}</p>
            <p class="text-xs text-gray-500 dark:text-gray-400 truncate">${terminal.cwd}</p>
          </div>
          <p class="text-xs text-gray-400 dark:text-gray-500">${createdTime}</p>
        </div>
      </div>
    `;
  }).join('');
}

function updateUserFilter() {
  const userFilter = document.getElementById('user-filter');
  const uniqueUsers = [...new Set(terminals.map(t => t.userId))];
  
  const currentValue = userFilter.value;
  
  userFilter.innerHTML = '<option value="">所有用户</option>' + 
    uniqueUsers.map(userId => `<option value="${userId}">${userId}</option>`).join('');
  
  if (uniqueUsers.includes(currentValue)) {
    userFilter.value = currentValue;
  }
}

async function selectTerminal(terminalId) {
  activeTerminalId = terminalId;
  updateTerminalList();
  
  const terminal = terminals.find(t => t.id === terminalId);
  if (!terminal) return;
  
  const commandInputContainer = document.getElementById('command-input-container');
  commandInputContainer.classList.remove('hidden');
  
  const container = document.getElementById('terminal-container');
  container.innerHTML = '';
  
  const wrapper = document.createElement('div');
  wrapper.className = 'h-full flex flex-col';
  
  const header = document.createElement('div');
  header.className = 'flex items-center justify-between p-4 border-b border-gray-700 bg-gray-900';
  header.innerHTML = `
    <div class="flex items-center gap-2">
      <span class="material-symbols-outlined text-green-400 text-lg">terminal</span>
      <p class="text-white text-sm">Terminal: ${terminal.id.substring(0, 8)} - ${terminal.cwd}</p>
    </div>
    <div class="flex items-center gap-4">
      <div class="flex items-center gap-2 text-sm">
        <span class="${terminal.status === 'active' ? 'text-green-400' : 'text-gray-400'}">●</span>
        <span class="text-white">${terminal.status}</span>
      </div>
      <button onclick="deleteTerminal('${terminal.id}')" class="px-3 py-1 text-xs font-medium text-white bg-red-600 rounded hover:bg-red-700 transition-colors">
        删除
      </button>
    </div>
  `;
  
  const terminalDiv = document.createElement('div');
  terminalDiv.id = `xterm-${terminalId}`;
  terminalDiv.className = 'flex-1 p-4';
  
  wrapper.appendChild(header);
  wrapper.appendChild(terminalDiv);
  container.appendChild(wrapper);
  
  if (!xtermInstances[terminalId]) {
    const term = new Terminal({
      cursorBlink: true,
      fontSize: 14,
      fontFamily: 'Menlo, Monaco, "Courier New", monospace',
      theme: {
        background: '#000000',
        foreground: '#ffffff',
      }
    });
    
    const fitAddon = new FitAddon.FitAddon();
    term.loadAddon(fitAddon);
    
    term.open(terminalDiv);
    fitAddon.fit();
    
    window.addEventListener('resize', () => fitAddon.fit());
    
    term.onData(async (data) => {
      await sendInput(terminalId, terminal.userId, data);
    });
    
    xtermInstances[terminalId] = { term, fitAddon };
    
    await loadTerminalOutput(terminalId, terminal.userId, term);
    
    setInterval(async () => {
      if (activeTerminalId === terminalId) {
        await loadTerminalOutput(terminalId, terminal.userId, term, true);
      }
    }, 1000);
  }
}

let lastReadLines = {};

async function loadTerminalOutput(terminalId, userId, term, incremental = false) {
  try {
    const since = incremental && lastReadLines[terminalId] ? lastReadLines[terminalId] : 0;
    const response = await fetch(`${API_BASE_URL}/terminals/${terminalId}/output?userId=${userId}&since=${since}`);
    const data = await response.json();
    
    if (data.success && data.data.output) {
      if (!incremental) {
        term.clear();
      }
      term.write(data.data.output);
      lastReadLines[terminalId] = data.data.nextReadFrom || 0;
    }
  } catch (error) {
    console.error('Failed to load terminal output:', error);
  }
}

async function sendInput(terminalId, userId, input) {
  try {
    await fetch(`${API_BASE_URL}/terminals/${terminalId}/input`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ userId, input })
    });
  } catch (error) {
    console.error('Failed to send input:', error);
  }
}

async function createTerminal(userId, cwd, shell) {
  try {
    const body = { userId, cwd };
    if (shell) body.shell = shell;
    
    const response = await fetch(`${API_BASE_URL}/terminals`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body)
    });
    
    const data = await response.json();
    
    if (data.success) {
      await fetchTerminals(currentUserId);
      selectTerminal(data.data.terminalId);
      return true;
    } else {
      alert(`错误: ${data.error.message}`);
      return false;
    }
  } catch (error) {
    console.error('Failed to create terminal:', error);
    alert('创建终端失败');
    return false;
  }
}

async function deleteTerminal(terminalId) {
  const terminal = terminals.find(t => t.id === terminalId);
  if (!terminal) return;
  
  showConfirmModal(`确定要删除终端 ${terminalId.substring(0, 8)} 吗？`, async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/terminals/${terminalId}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: terminal.userId })
      });
      
      const data = await response.json();
      
      if (data.success) {
        if (xtermInstances[terminalId]) {
          xtermInstances[terminalId].term.dispose();
          delete xtermInstances[terminalId];
        }
        
        if (activeTerminalId === terminalId) {
          activeTerminalId = null;
          document.getElementById('terminal-container').innerHTML = `
            <div class="h-full flex items-center justify-center text-gray-400">
              <div class="text-center">
                <span class="material-symbols-outlined text-6xl mb-4">terminal</span>
                <p class="text-lg">选择一个终端或创建新终端</p>
              </div>
            </div>
          `;
        }
        
        await fetchTerminals(currentUserId);
      } else {
        alert(`错误: ${data.error.message}`);
      }
    } catch (error) {
      console.error('Failed to delete terminal:', error);
      alert('删除终端失败');
    }
  });
}

async function stopAllTerminals() {
  const terminalsToStop = currentUserId 
    ? terminals.filter(t => t.userId === currentUserId)
    : terminals;
  
  if (terminalsToStop.length === 0) {
    alert('没有终端需要停止');
    return;
  }
  
  const message = currentUserId 
    ? `确定要停止用户 "${currentUserId}" 的所有 ${terminalsToStop.length} 个终端吗？`
    : `确定要停止所有 ${terminalsToStop.length} 个终端吗？`;
  
  showConfirmModal(message, async () => {
    for (const terminal of terminalsToStop) {
      try {
        await fetch(`${API_BASE_URL}/terminals/${terminal.id}`, {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ userId: terminal.userId })
        });
        
        if (xtermInstances[terminal.id]) {
          xtermInstances[terminal.id].term.dispose();
          delete xtermInstances[terminal.id];
        }
      } catch (error) {
        console.error(`Failed to stop terminal ${terminal.id}:`, error);
      }
    }
    
    activeTerminalId = null;
    document.getElementById('terminal-container').innerHTML = `
      <div class="h-full flex items-center justify-center text-gray-400">
        <div class="text-center">
          <span class="material-symbols-outlined text-6xl mb-4">terminal</span>
          <p class="text-lg">选择一个终端或创建新终端</p>
        </div>
      </div>
    `;
    
    await fetchTerminals(currentUserId);
  });
}

function showConfirmModal(message, onConfirm) {
  const modal = document.getElementById('confirm-modal');
  const messageEl = document.getElementById('confirm-message');
  
  messageEl.textContent = message;
  modal.classList.remove('hidden');
  
  const yesBtn = document.getElementById('confirm-yes');
  const noBtn = document.getElementById('confirm-no');
  
  const cleanup = () => {
    modal.classList.add('hidden');
    yesBtn.replaceWith(yesBtn.cloneNode(true));
    noBtn.replaceWith(noBtn.cloneNode(true));
  };
  
  document.getElementById('confirm-yes').onclick = () => {
    cleanup();
    onConfirm();
  };
  
  document.getElementById('confirm-no').onclick = cleanup;
}

document.getElementById('new-terminal-btn').addEventListener('click', () => {
  document.getElementById('new-terminal-modal').classList.remove('hidden');
});

document.getElementById('cancel-modal').addEventListener('click', () => {
  document.getElementById('new-terminal-modal').classList.add('hidden');
  document.getElementById('new-terminal-form').reset();
});

document.getElementById('new-terminal-form').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  const userId = document.getElementById('userId').value;
  const cwd = document.getElementById('cwd').value;
  const shell = document.getElementById('shell').value;
  
  const success = await createTerminal(userId, cwd, shell);
  
  if (success) {
    document.getElementById('new-terminal-modal').classList.add('hidden');
    document.getElementById('new-terminal-form').reset();
  }
});

document.getElementById('stop-all-btn').addEventListener('click', stopAllTerminals);

document.getElementById('user-filter').addEventListener('change', (e) => {
  currentUserId = e.target.value;
  fetchTerminals(currentUserId);
});

document.getElementById('theme-toggle').addEventListener('click', () => {
  document.documentElement.classList.toggle('dark');
  const icon = document.querySelector('#theme-toggle .material-symbols-outlined');
  icon.textContent = document.documentElement.classList.contains('dark') ? 'wb_sunny' : 'dark_mode';
});

async function sendCommandFromInput() {
  if (!activeTerminalId) return;
  
  const input = document.getElementById('command-input');
  const command = input.value.trim();
  
  if (!command) return;
  
  const terminal = terminals.find(t => t.id === activeTerminalId);
  if (!terminal) return;
  
  await sendInput(activeTerminalId, terminal.userId, command + '\n');
  input.value = '';
}

document.getElementById('send-command-btn').addEventListener('click', sendCommandFromInput);

document.getElementById('command-input').addEventListener('keypress', (e) => {
  if (e.key === 'Enter') {
    sendCommandFromInput();
  }
});

let AI_PROMPT = '';

async function loadPrompt() {
  try {
    const response = await fetch('/PROMPT.md');
    AI_PROMPT = await response.text();
  } catch (err) {
    console.error('Failed to load prompt:', err);
    AI_PROMPT = '# 加载失败\n\n请刷新页面重试';
  }
}

loadPrompt();

document.getElementById('nav-dashboard').addEventListener('click', () => {
  document.querySelectorAll('.nav-item').forEach(item => {
    item.classList.remove('bg-primary/10', 'text-primary', 'dark:bg-primary/20');
    item.classList.add('hover:bg-gray-200', 'dark:hover:bg-gray-800', 'text-gray-700', 'dark:text-gray-300');
  });
  
  document.getElementById('nav-dashboard').classList.add('bg-primary/10', 'text-primary', 'dark:bg-primary/20');
  document.getElementById('nav-dashboard').classList.remove('hover:bg-gray-200', 'dark:hover:bg-gray-800', 'text-gray-700', 'dark:text-gray-300');
  
  document.getElementById('dashboard-view').classList.remove('hidden');
  document.getElementById('prompt-view').classList.add('hidden');
  document.getElementById('user-filter-container').classList.remove('hidden');
  document.getElementById('new-terminal-btn').classList.remove('hidden');
  document.getElementById('stop-all-btn').classList.remove('hidden');
});

document.getElementById('nav-prompt').addEventListener('click', () => {
  document.querySelectorAll('.nav-item').forEach(item => {
    item.classList.remove('bg-primary/10', 'text-primary', 'dark:bg-primary/20');
    item.classList.add('hover:bg-gray-200', 'dark:hover:bg-gray-800', 'text-gray-700', 'dark:text-gray-300');
  });
  
  document.getElementById('nav-prompt').classList.add('bg-primary/10', 'text-primary', 'dark:bg-primary/20');
  document.getElementById('nav-prompt').classList.remove('hover:bg-gray-200', 'dark:hover:bg-gray-800', 'text-gray-700', 'dark:text-gray-300');
  
  document.getElementById('dashboard-view').classList.add('hidden');
  document.getElementById('prompt-view').classList.remove('hidden');
  document.getElementById('user-filter-container').classList.add('hidden');
  document.getElementById('new-terminal-btn').classList.add('hidden');
  document.getElementById('stop-all-btn').classList.add('hidden');
  
  document.getElementById('prompt-content').textContent = AI_PROMPT;
});

document.getElementById('copy-prompt-btn').addEventListener('click', async () => {
  try {
    await navigator.clipboard.writeText(AI_PROMPT);
    const btn = document.getElementById('copy-prompt-btn');
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<span class="material-symbols-outlined text-base">check</span>已复制！';
    btn.classList.remove('bg-primary');
    btn.classList.add('bg-green-600');
    
    setTimeout(() => {
      btn.innerHTML = originalHTML;
      btn.classList.remove('bg-green-600');
      btn.classList.add('bg-primary');
    }, 2000);
  } catch (err) {
    console.error('Failed to copy:', err);
    alert('复制失败，请手动复制');
  }
});

fetchTerminals();
